package org.example.forum.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * @return     true 继续流程 <br/>  false 流程中断
     * @throws Exception
     */
    //设置一个自定路路径统一管理 防止页面地址改变 代码修改复杂
    @Value("${xz-forum.login.url}")
    private String defaultURL;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession();
        //判断session是否为空
        //不为空
        if(session != null && session.getAttribute(AppConfig.USER_SESSION)!= null){
            return true;
        }
        //Url校验
        if(!defaultURL.startsWith("/")){
            defaultURL =  "/"+defaultURL;
        }
        //为空跳转登录页面
        response.sendRedirect(defaultURL);
        //终端流程
        return false;
    }
}
